package com.cskaoyan.service.wx;


import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.wx.FastAddBO;
import com.cskaoyan.bean.bo.wx.UpdateCheckedBO;
import com.cskaoyan.bean.bo.wx.UpdateNumInCartBO;
import com.cskaoyan.bean.vo.wx.CartCheckoutVO;
import com.cskaoyan.bean.vo.wx.CartIndexVo;
import com.cskaoyan.bean.vo.wx.CartTotalVO;
import com.cskaoyan.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import com.cskaoyan.bean.MarketCart;
import com.cskaoyan.bean.MarketCartExample;
import com.cskaoyan.mapper.MarketCartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.EmptyStackException;
import java.util.List;

/**
 * @author by yxy_8175@163.com
 * @Description TODO
 * @Date 2022-11-22 17:38
 */

@Service
public class CartServiceImpl implements CartService{

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;

    @Override
    public int getGoodsCountInCart(Integer userId) {

        List <MarketCart> marketCarts = marketCartMapper.selectCountByUserId(userId);
        int count = 0;
        for (MarketCart marketCart : marketCarts) {
            count += marketCart.getNumber();
        }
        return count;
    }

    @Transactional
    @Override
    public int addGoods(Integer userId, Integer goodsId, Integer number, Integer productId) {

        int count = marketCartMapper.selectGoodsIdCount(userId,productId);

        if(count != 0){
            int curNum = marketCartMapper.selectCurNum(userId,productId);
            int newNum = curNum + number;
            marketCartMapper.updateNumAndChecked(productId,newNum);
        }else {
            String goodsSn = marketGoodsMapper.selectGoodsSn(goodsId);
            String goodsName = marketGoodsMapper.selectGoodsName(goodsId);
            Double price = marketGoodsProductMapper.selectPrice(productId);
            String specifications = marketGoodsProductMapper.selectSpecifications(productId);
            String url = marketGoodsProductMapper.selectUrl(productId);

            MarketCart marketCart = new MarketCart(null, userId, goodsId, goodsSn, goodsName, productId, price, number, specifications, true, url, null, null, false);
            System.out.println(marketCart);
            int i = marketCartMapper.insertGoods(marketCart);
        }
        int res = marketCartMapper.selectCount(userId);
        return res;
    }

    @Override
    public CartIndexVo getIndex(Integer userId) {
        List<MarketCart> cartList = marketCartMapper.selectByUserId(userId);
        Double checkedGoodsAmount = 0.0;
        Integer checkedGoodsCount = 0;
        Double goodsAmount = 0.0;
        Integer goodsCount = 0;
        for (MarketCart marketCart : cartList) {
            if(marketCart.getChecked().equals(1)){
                checkedGoodsCount += marketCart.getNumber();
                checkedGoodsAmount += (marketCart.getPrice() * marketCart.getNumber());
            }

            goodsAmount += (marketCart.getPrice() * marketCart.getNumber());
            goodsCount += marketCart.getNumber();
        }

        CartTotalVO cartTotalVO = new CartTotalVO(checkedGoodsAmount,checkedGoodsCount,goodsAmount,goodsCount);
        CartIndexVo cartIndexVo = new CartIndexVo(cartList,cartTotalVO);

        return cartIndexVo;
    }

    @Override
    public CartIndexVo updateChecked(Integer userId, UpdateCheckedBO updateCheckedBO) {
        Boolean isChecked = updateCheckedBO.getIsChecked();
        List<Integer> productIds = updateCheckedBO.getProductIds();

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.setDistinct(true);
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();

        criteria.andUserIdEqualTo(userId);
        criteria.andProductIdIn(productIds);
        marketCartMapper.updateCheckedByExample(isChecked,marketCartExample);

        CartIndexVo cartIndexVo = this.getIndex(userId);
        return cartIndexVo;
    }

    @Override
    public void updateNum(Integer userId, UpdateNumInCartBO updateNumInCartBO) {
        Integer id = updateNumInCartBO.getId();
        Integer number = updateNumInCartBO.getNumber();

        MarketCart marketCart = marketCartMapper.selectByPrimaryKey(id);
        if(marketCart.getNumber().equals(number)){  //已经是1的情况下再给个1 -->删除该商品
            marketCartMapper.updateDeleted(id);
        }else {
            marketCartMapper.updateNum(id,number);
        }

        //CartIndexVo cartIndexVo = this.getIndex(userId);
    }

    @Override
    public CartIndexVo updatedeleted(Integer userId, UpdateCheckedBO updateCheckedBO) {
        List<Integer> productIds = updateCheckedBO.getProductIds();

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.setDistinct(true);
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();

        criteria.andUserIdEqualTo(userId);
        criteria.andProductIdIn(productIds);
        marketCartMapper.updateDeletedByExample(marketCartExample);

        CartIndexVo cartIndexVo = this.getIndex(userId);
        return cartIndexVo;
    }

    @Override
    public int fastAddCart(Integer userId, FastAddBO fastAddBO) {
        Integer goodsId = fastAddBO.getGoodsId();
        Integer number = fastAddBO.getNumber();
        Integer productId = fastAddBO.getProductId();
        MarketCart marketCart = marketCartMapper.selectByUserIdAndGoodsId(userId,goodsId); //用户id和商品id唯一确定一条购物车记录

        if(null != marketCart){ //如果购物车里已经有这个商品,那么更新数据库中的num
           marketCartMapper.updateNum(marketCart.getId(),number);
           return marketCart.getId();
        }else {
            this.addGoods(userId,goodsId,number,productId); //新增一条购物车记录
            MarketCart newMarketCart = marketCartMapper.selectByUserIdAndGoodsId(userId,goodsId);
            return newMarketCart.getId();
        }
    }

    @Override
    public CartCheckoutVO getCartCheckVO(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer grouponRulesId, Integer userId) {
        CartCheckoutVO cartCheckoutVO = new CartCheckoutVO();

        if (addressId.equals(0)) {   //如果没提供地址
            MarketAddress defaultAddress = marketAddressMapper.selectDefault(userId);  //找出当前用户的默认地址
            Integer addressId1 = defaultAddress.getId();
            cartCheckoutVO.setAddressId(addressId1);
            cartCheckoutVO.setCheckedAddress(defaultAddress);
        } else {
            MarketAddress checkedAddress = marketAddressMapper.selectByPrimaryKey(addressId);
            cartCheckoutVO.setAddressId(addressId);
            cartCheckoutVO.setCheckedAddress(checkedAddress);
        }

        List<MarketCart> checkedGoodsList = marketCartMapper.selectAllChecked(userId); //找出当前用户购物车选中的所有商品
        cartCheckoutVO.setCheckedGoodsList(checkedGoodsList);

        Double goodsTotalPrice = 0.0;
        for (MarketCart marketCart : checkedGoodsList) {
            goodsTotalPrice += (marketCart.getNumber() * marketCart.getPrice());
        }

        //System.out.println(goodsTotalPrice);

        cartCheckoutVO.setGoodsTotalPrice(goodsTotalPrice);
        Double freightPrice = 8.0;
        if (goodsTotalPrice >= 88) {
            freightPrice = 0.0;
        }
        cartCheckoutVO.setFreightPrice(freightPrice);
        Double orderTotalPrice = 0.0;  //订单总价等于商品总价加运费
        orderTotalPrice = goodsTotalPrice + freightPrice;
        cartCheckoutVO.setOrderTotalPrice(orderTotalPrice);

        int availableCouponLength = marketCouponUserMapper.selectAvailable(userId, goodsTotalPrice);//商品总价大于一定数目才可使用优惠券
        cartCheckoutVO.setAvailableCouponLength(availableCouponLength);
        cartCheckoutVO.setCouponId(couponId);
        cartCheckoutVO.setUserCouponId(userCouponId);
        cartCheckoutVO.setGrouponRulesId(grouponRulesId);
        cartCheckoutVO.setCartId(cartId);

        Double couponPrice = marketCouponMapper.selectCouponPrice(couponId);
        if (null == couponPrice) {
            couponPrice = 0.0;
        }
        Double grouponPrice = marketGrouponRulesMapper.selectgrouponPrice(grouponRulesId);
        if (null == grouponPrice) {
            grouponPrice = 0.0;
        }

        Double actualPrice = 0.0;
        actualPrice = orderTotalPrice - couponPrice - grouponPrice;
        cartCheckoutVO.setCouponPrice(couponPrice);
        cartCheckoutVO.setGrouponPrice(grouponPrice);
        cartCheckoutVO.setActualPrice(actualPrice);
        return cartCheckoutVO;

    }

    @Override
    public List<MarketCart> queryUidAndChecked(Integer userId) {
        MarketCartExample example = new MarketCartExample();
        example.or()
                .andUserIdEqualTo(userId)
                // 是否为选中状态
                .andCheckedEqualTo(true)
                // 是否已删除
                .andDeletedEqualTo(false);
        return marketCartMapper.selectByExample(example);
    }

    @Override
    public MarketCart findById(Integer userId, Integer cartId) {
        MarketCartExample example = new MarketCartExample();
        example.or()
                .andUserIdEqualTo(userId)
                .andIdEqualTo(cartId)
                // 是否为选中状态
                .andCheckedEqualTo(true)
                // 是否已删除
                .andDeletedEqualTo(false);
        return  marketCartMapper.selectOneByExample(example);
    }
}
